package com.bird.ecmainmenu3.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.TextureView;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.bird.ecmainmenu3.R;
import com.bird.ecmainmenu3.base.OnMainUiListener;
import com.bird.ecmainmenu3.presenter.AppsManager;
import com.bird.ecmainmenu3.presenter.MainPresenter;
import com.bird.ecmainmenu3.util.Utils;

import java.lang.ref.WeakReference;
import java.util.Objects;
import java.util.Set;

public class MainActivity extends AppCompatActivity implements OnMainUiListener,View.OnClickListener {
    private static final String TAG = Utils.TAG + MainActivity.class.getSimpleName();
    private final Handler mMainHandler = new Handler(Looper.getMainLooper());
    private MainPresenter mMainPresenter;
    private WeakReference<TextureView> mTextureViewRef;
    private final TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
            Log.d(TAG, "onSurfaceTextureAvailable: " + surface);
            if (mMainPresenter != null) {
                mMainPresenter.createMediaPlayer(surface);
            }
        }

        @Override
        public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surfaceTexture) {
            if (mMainPresenter != null) {
                mMainPresenter.releaseMediaPlayer();
            }
            return true;
        }

        @Override
        public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surfaceTexture, int i, int i1) {

        }

        @Override
        public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surfaceTexture) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        init();
    }

    private void init() {
        initViews();
        initPresenter();
    }

    private void initViews() {
        initTextureView();
        initControlViews();
        initDateTimeViews();
    }

    private void initDateTimeViews() {
        long currentTime = System.currentTimeMillis();
        Log.d(TAG, "initDateTimeViews: " + currentTime);

        String dateFormat = getResources().getString(R.string.date_format);
        String timeFormat = getResources().getString(R.string.time_format);

        CharSequence date = DateFormat.format(dateFormat, currentTime);
        Log.d(TAG, "initDateTimeViews: " + date);
        if (date.length() > 0) {
            updateDateView(date.toString());
        }

        CharSequence time = DateFormat.format(timeFormat, currentTime);
        Log.d(TAG, "initDateTimeViews: " + time);
        if (time.length() > 0) {
            updateTimeView(time.toString());
        }
    }

    private void updateDateView(String date) {
        mMainHandler.post(() -> ((TextView)findViewById(R.id.tv_date_id)).setText(date));
    }

    private void updateTimeView(String time) {
        mMainHandler.post(() -> ((TextView)findViewById(R.id.tv_time_id)).setText(time));
    }

    private void initPresenter() {
        mMainPresenter = new MainPresenter(getApplicationContext());
        mMainPresenter.setCallback(this);
    }

    @Override
    public void onDateTimeChanged() {
        initDateTimeViews();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    private void initTextureView() {
        mTextureViewRef = new WeakReference<>(findViewById(R.id.textureView_id));
        mTextureViewRef.get().setSurfaceTextureListener(mSurfaceTextureListener);
        mTextureViewRef.get().setOpaque(false);
    }

    private void initControlViews() {
        findViewById(R.id.iv_bg_id).setOnClickListener(this);

        ImageView musicView = findViewById(R.id.iv_music_id);
        musicView.setOnClickListener(this);
        musicView.post(() -> startWaveBounceAnimation(musicView));

        ImageView phoneView = findViewById(R.id.iv_phone_id);
        phoneView.setOnClickListener(this);
        phoneView.post(() -> startWaveBounceAnimation(phoneView));

        ImageView navigationView = findViewById(R.id.iv_navigation_id);
        navigationView.setOnClickListener(this);
        navigationView.post(() -> startWaveBounceAnimation(navigationView));

        ImageView cameraView = findViewById(R.id.iv_camera_id);
        cameraView.setOnClickListener(this);
        cameraView.post(() -> startWaveBounceAnimation(cameraView));

        ImageView connectionView = findViewById(R.id.iv_connection_id);
        connectionView.setOnClickListener(this);
        connectionView.post(() -> startWaveBounceAnimation(connectionView));
    }

    private void startWaveBounceAnimation(@NonNull View view) {
        ObjectAnimator animator;
        View layout = findViewById(R.id.ll_bottom_id);
        float transY = ((float) (layout.getHeight() - view.getHeight()));
        animator = ObjectAnimator.ofFloat(view,"translationY", 0f, transY*0.20f);
        animator.setInterpolator(new BounceInterpolator());
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setRepeatMode(ValueAnimator.REVERSE);
        animator.setDuration(5000);
        animator.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseTextureView();
        if (mMainPresenter != null) {
            mMainPresenter.destroy();
            mMainPresenter = null;
        }
        Log.d(TAG, "onDestroy: ");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Log.d(TAG, "KEYCODE_BACK");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View view) {
        if (view == null) {
            Log.e(TAG, "onClick: view is null");
        } else {
            if (view.getId() == R.id.iv_music_id) {
                Log.d(TAG, "onClick: iv_music_id");
                if (mMainPresenter != null) {
                    mMainPresenter.startApp(Utils.KUWO_PKG, Utils.KUWO_CLS);
                }
            } else if (view.getId() == R.id.iv_phone_id) {
                Log.d(TAG, "onClick: iv_phone_id");
                if (mMainPresenter != null) {
                    mMainPresenter.startApp(Utils.PHONE_PKG, Utils.PHONE_CLS);
                }
            } else if (view.getId() == R.id.iv_navigation_id) {
                Log.d(TAG, "onClick: iv_navigation_id");
                if (mMainPresenter != null) {
                    mMainPresenter.startApp(Utils.AUTONAVI_PKG, Utils.AUTONAVI_CLS);
                }
            } else if (view.getId() == R.id.iv_camera_id) {
                Log.d(TAG, "onClick: iv_camera_id");
                if (mMainPresenter != null) {
                    mMainPresenter.startApp(Utils.DVR_PKG, Utils.DVR_CLS);
                }
            } else if (view.getId() == R.id.iv_connection_id) {
                Log.d(TAG, "onClick: iv_connection_id");
                if (mMainPresenter != null) {
                    mMainPresenter.startApp(Utils.CONNECTION_PKG, Utils.CONNECTION_CLS);
                }
            } else if (view.getId() == R.id.iv_bg_id) {
                Log.d(TAG, "onClick: iv_bg_id");
                startAppListActivity();
            }
        }
    }

    private void releaseTextureView() {
        if (mTextureViewRef.get() != null) {
            mTextureViewRef.get().setSurfaceTextureListener(null);
            mTextureViewRef = null;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (Objects.equals(intent.getAction(), Intent.ACTION_MAIN)) {
            Set<String> categories = intent.getCategories();
            for (String category : categories) {
                if (Objects.equals(category, Utils.CATEGORY_MAIN_MENU_BIRD)) {
                    Log.d(TAG, "onNewIntent: CATEGORY_MAIN_MENU_BIRD");
                    showAppList();
                }
            }
        }
    }

    private void showAppList() {
        if (AppsManager.getInstance().isAppListShowing()) {
            AppsManager.getInstance().setAppListShowing(false);
        } else {
            AppsManager.getInstance().setAppListShowing(true);
            startAppListActivity();
        }
    }

    private void startAppListActivity() {
        Intent intent2 = new Intent(this, AppListActivity.class);
        intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent2.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        this.startActivity(intent2);
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d(TAG, "onConfigurationChanged: " + newConfig);
    }
}